<?php

namespace Frieza\Modules\Lottery\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Doraemon\model\Lottery\LotteryActivity;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;


class ActivityController extends Controller
{

    const PAGE_SIZE = 20;


    public function index(Request $request, Content $content)
    {
        $page = $request->input('page', 1);
        $perPage = $request->input('per_page');

        $limit = [
            ($page - 1) * $perPage,
            $perPage
        ];


        $where = [
            "AND" => [
                "a_status" => LotteryActivity::STATUS_NORMAL,
            ],
            'ORDER' => [
                'id' => 'DESC'
            ],
            'LIMIT' => $limit,
        ];

        $result = [];
        $result['list'] = LotteryActivity::selectByWhere($where);

        unset($where['ORDER']);
        unset($where['LIMIT']);
        $result['total'] = LotteryActivity::selectCount($where);
        $grid = new pGridDataModel($result['list'], $result['total'], [
            'per_page' => $perPage
        ]);
        $gridList = Admin::grid($grid,
            function (Grid $grid) {
                $grid->disableExport();
                $grid->disableRowSelector();
                $grid->disableFilter();
                $grid->column('id');
                $grid->column('lottery_type', "活动创建渠道")->using(['0' => '后台创建', '1' => '直播创建']);
                $grid->column('award_title', '活动标题');
                $grid->column('award_remark', '活动描述');
                $grid->column('', '抽奖期数')->display(function () {
                    $html = '<a href="' . url('/admin/lottery/activity/' . $this->id . '/series/index') . '">期数列表</a>';
                    return $html;
                })->width(100);
                $grid->column('addtime', '添加时间');
                $grid->column('edittime', '修改时间');
                $grid->column('admin_id', '操作人')->display(function () {
                    if (!$this->admin_id) {
                        return '暂无';
                    } else {
                        return Admin::user()->find($this->admin_id)->name;
                    }
                });
            });

        $content->row($gridList);
        return $content
            ->header('抽奖活动列表')
            ->description(' ')
            ->breadcrumb(['text' => 'lottery']);
    }

    //新建/编辑页面
    public function edit(Content $content, $id = 0)
    {
        $tab = new Tab();
        if ($id > 0) {
            $title = '编辑抽奖活动';
        } else {
            $title = '创建抽奖活动';
        }
        $tab->add("$title", $this->editAction($id));
        return $content
            ->header('投票管理')
            ->breadcrumb(
                [
                    'text' => '抽奖活动列表',
                    'url' => '/activity/index'
                ],
                ['text' => "$title"]
            )
            ->body($tab);
    }

    private function editAction($id = 0)
    {
        if ($id > 0) {
            $data = LotteryActivity::getActivityById($id);
            $form = new Form($data);
            $form->hidden('id');
        } else {
            $form = new Form();
        }
        $form->text('award_title', '抽奖活动标题')->required('活动标题必填');
        $form->textarea('award_remark', '抽奖活动描述')->required('活动描述必填');
        $form->action('/admin/lottery/activity/index/save');
        return $form;
    }

    public function saveSubmit(Request $request)
    {
        $params = $request->all();
        $data = [
            'award_title' => $params['award_title'],
            'award_remark' => $params['award_remark'],
            'a_status' => LotteryActivity::STATUS_NORMAL,
            'admin_id' => Admin::user()->id,
        ];

        if (isset($params['id']) && $params['id']) {
            //编辑
            $data['edittime'] = date('Y-m-d H:i:s', time());
            $rs = LotteryActivity::editData($params['id'], $data);

        } else {
            //创建
            $data['addtime'] = date('Y-m-d H:i:s', time());
            $rs = LotteryActivity::addData($data);
        }
        if ($rs) {
            $success = new MessageBag([
                'title' => '保存成功,可以去设置期数啦'
            ]);
            return redirect('/admin/lottery/activity/index')->with(compact('success'));

        } else {
            $error = new MessageBag([
                'title' => '保存失败'
            ]);
            return back()->with(compact('error'));
        }
    }

    public function delActivity(Request $request, $id = 0)
    {
        try {
            if ($id) {
                LotteryActivity::editData(['id' => $id], ['a_status' => LotteryActivity::STATUS_DELETE]);
                return response()->json([
                    'status' => true,
                    'message' => "操作成功",
                ]);

            } else {
                throw new \Exception('不存在的id');
            }
        } catch (\Exception $e) {
            return response()->json([
                'status' => false,
                'message' => "操作失败",
            ]);
        }
        return response()->json($success);
    }

}
